import axios from 'axios'

//给axios一个默认类型
const service = axios.create({
    responseType:'arraybuffer'
})

//请求拦截器
service.interceptors.request.use(config=>{
  config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr')
    return config
},error => {
    console.log(error)
})

service.interceptors.response.use(res=>{
    const headers = res.headers //拿到头部信息
    let reg = RegExp(/application\/json/)
    //判断数据以什么形式返回 流或者字符串
    if (headers['content-type'].match(reg)){//判断content-type是否与正则表达式匹配
        res.data = unitToString(res.data)//匹配就是普通的接口请求  转换为字符串
    }else {
        const fileDownLoad = require('js-file-download')
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
        let contentType = headers['content-type']
        fileName = decodeURIComponent(fileName)
        fileDownLoad(res.data,fileName,contentType)
    }
},error => {
    console.log(error)
})

function unitToString(unitArray) {
    let encodedString = String.fromCharCode.apply(null,new Uint8Arry(unitArray))//编码
    let decodedString = decodeURIComponent(escape(encodedString))//节码
    return JSON.parse(decodedString)
}

let base = ''
export const downloadRequest=(url,params)=>{
    return service({
        method:'get',
        url:`${base}${url}`,
        data:params
    })
}

export default service